/*
 * All rights Reserved, Designed By cloudland Copyright(C) 2010-2014
 *
 * fileName:  IndexReadHandlerImpl.java
 * author:  lei
 * Company:  Cloudland Studio
 * Createdate:  2013-9-19 下午9:31:25
 *   
 * Modification  History:
 *     Date           Author        Version        
 * -------------------------------------------
 * 2013-9-19          Lei            1.0        
 *
 * Why & What is modified:
 * 1.0: 文件创建
 */
package org.cloudland.search.handler.support;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Version;
import org.cloudland.search.exception.ConstantsException;
import org.cloudland.search.exception.SearchException;
import org.cloudland.search.handler.IndexRead;
import org.cloudland.search.handler.ResultSet;

 /**
 * <pre> 
 * 索引读操作接口实现类
 * </pre>
 * @ClassName  IndexReadHandlerImpl
 * @author  lei
 * @version  %I%, %G%
 * @see  
 * @since   JDK1.6
 *
 */
public class IndexReadHandlerImpl implements IndexRead {

	/**
	 * LOGGER 日志
	 */
	private static Logger LOGGER = Logger.getLogger(IndexReadHandlerImpl.class);
	
    /**
     * search 
     */
    private IndexSearcher searcher;
    
    /**
     * analyzer
     */
    private Analyzer analyzer;
    
	/** 
	 * default constructor
	 */
	public IndexReadHandlerImpl(IndexSearcher search, Analyzer an) {
		this.searcher = search;
		this.analyzer = an;
	}
	
    /**
     * @param content
     * @return
     */
    public ResultSet[] query(String content)
    {
    	ResultSet[] result = null;
    	
    	try {
	    	QueryParser p = new QueryParser(Version.LUCENE_42, "detail", analyzer);
	        Query q = p.parse(content);
	        TopDocs docs = searcher.search(q, null, 1000);   
	        
	        ScoreDoc[] hits = docs.scoreDocs;
	        if (hits.length > 0) {
	        	 result = new ResultSetImpl[hits.length];
	        	 int index = 0;
	             for (ScoreDoc d : hits) {
	            	 result[index] = new ResultSetImpl(d.doc, d.score, searcher.doc(d.doc));
	            	 index++;
	             }
	        }
    	} catch (Exception e) {
    		LOGGER.error("Indexed query exception. ", e);
    		throw new SearchException(ConstantsException.SEARCH_QUERY_SB0006, e);
    	}
        
        return result;
    }

}
